package hr.eon.server;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Context class which is wrapper around Spring Application Context.
 * It setup spring context on start and offers loader for getting JMS messages
 * handlers depending on received message class type.
 * 
 * @author mjovanovic
 * @since 0.0.1
 */
public final class EonContext {

    private EonContext() {}

    private static final Logger LOGGER = Logger.getLogger( EonContext.class );

    private static ApplicationContext appCtx;

    public static void setup() {
        LOGGER.info( "Starting Eon context.." );
        appCtx = new ClassPathXmlApplicationContext( "classpath:appCtx.xml" );
        LOGGER.info( "Eon context started." );
    }

    public static Object getBean( String name ) {
        return appCtx.getBean( name );
    }

    public static Object getBean( Class<?> clazz ) {
        return appCtx.getBean( clazz );
    }

    public static Object getMessageHandler( Class<?> clazz ) {
        return getBean( getHandlerName( clazz.getSimpleName() ) );
    }

    private static String getHandlerName( String message ) {
        char newFirst = (char) ( message.charAt( 0 ) + 32 );
        return new StringBuilder().append( newFirst ).append( message.substring( 1 ) ).append( "Handler" ).toString();
    }

}
